package com.ylz.sjzx.sio.core;

import com.ylz.sjzx.sio.common.core.core.IAdapter;
import com.ylz.sjzx.sio.common.core.core.Interceptor.InterceptorChain;
import com.ylz.sjzx.sio.common.core.core.SioBase;
import com.ylz.sjzx.sio.common.core.core.container.ContainerManager;
import com.ylz.sjzx.sio.common.core.exception.SioThrowException;
import com.ylz.sjzx.sio.common.core.utils.GsonUtil;
import com.ylz.sjzx.sio.core.group.model.CmdMessage;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author wiqi
 * @version 1.0
 * @date 2020/12/9
 */
public abstract class CmdBaseAdapter implements IAdapter {
    /**
     * logger
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 抽象类
     *
     * @return
     */
    @Override
    public abstract void process() throws Exception;

    @SneakyThrows
    @Override
    public void invoke() {
        //拦截器
        InterceptorChain interceptorChain = ContainerManager.getInterceptorChain();
        try {
            //拦截器处理
            interceptorChain.preHandle();
            //业务处理
            this.process();

            //后置处理，逆序执行拦截器
            interceptorChain.postHandle();
        } catch (Throwable e) {
            this.logger.error("netty adapter-service exception -Error param:{}", SioBase.getParam(), e);
            //吃掉异常
            SioBase.setException(e);
            //如果是SioThrowException 则抛出 所以针对异常 要确定抛出才抛出处理 否则吃掉 由后置处理解决
            if (e instanceof SioThrowException) {
                throw e;
            }
        } finally {
            interceptorChain.afterCompletion();
        }
    }

    /**
     * 获取param
     * 注：用getFirstParam 替代
     *
     * @return
     */
    @Deprecated
    public <T> T getParam(Class<T> clazz) {
        CmdMessage param = (CmdMessage) SioBase.getParam();
        return GsonUtil.json2Bean(param.getMessage(), clazz);
    }

    /**
     * 获取param
     *
     * @return
     */
    public Object getParam() {
        return SioBase.getParam();
    }


    /**
     * 获取param
     *
     * @return
     */
    public Map getMapParam() {
        return (Map) SioBase.getParam();
    }

}
